import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { useCache } from './useCache'
import { usePerformance } from './usePerformance'

export interface TableConfig<T = any> {
  fetchApi: (params?: any) => Promise<{ data: T[]; total: number }>
  createApi?: (data: any) => Promise<any>
  updateApi?: (id: string | number, data: any) => Promise<any>
  deleteApi?: (id: string | number) => Promise<any>
  pageSize?: number
  enablePagination?: boolean
  enableSort?: boolean
  cacheKey?: string
  enableCache?: boolean
  cacheTTL?: number
  defaultSort?: { prop: string; order: 'ascending' | 'descending' }
}

export interface UseTableReturn<T = any> {
  // 状态
  loading: Ref<boolean>
  tableData: Ref<T[]>
  currentPage: Ref<number>
  pageSize: Ref<number>
  total: Ref<number>
  dialogVisible: Ref<boolean>
  dialogTitle: Ref<string>
  isEdit: Ref<boolean>
  currentItem: any
  
  // 方法
  fetchData: (forceRefresh?: boolean) => Promise<void>
  handleSizeChange: (size: number) => void
  handleCurrentChange: (page: number) => void
  handleAdd: (title?: string) => void
  handleEdit: (item: T, title?: string) => void
  handleDelete: (id: string | number, confirmText?: string) => Promise<void>
  handleSubmit: (formRef?: FormInstance) => Promise<void>
  resetForm: () => void
  
  // 计算属性
  hasData: ComputedRef<boolean>
  isEmpty: ComputedRef<boolean>
}

export function useTable<T = any>(config: TableConfig<T>): UseTableReturn<T> {
  const {
    fetchApi,
    createApi,
    updateApi,
    deleteApi,
    pageSize: defaultPageSize = 10,
    enablePagination = true,
    enableSort = false,
    cacheKey = 'table_data',
    enableCache = true,
    cacheTTL = 5 * 60 * 1000, // 5 minutes
    defaultSort
  } = config

  // 初始化缓存和性能监控
  const cache = useCache({ ttl: cacheTTL })
  const { measureApiCall } = usePerformance()

  // 响应式状态
  const loading = ref(false)
  const tableData = ref<T[]>([])
  const currentPage = ref(1)
  const pageSize = ref(defaultPageSize)
  const total = ref(0)
  const dialogVisible = ref(false)
  const dialogTitle = ref('')
  const isEdit = ref(false)
  const currentItem = reactive<any>({})

  // 计算属性
  const hasData = computed(() => tableData.value.length > 0)
  const isEmpty = computed(() => !loading.value && tableData.value.length === 0)

  // 获取数据
  const fetchData = async (forceRefresh = false) => {
    loading.value = true
    try {
      const params: any = {}
      
      if (enablePagination) {
        params.page = currentPage.value
        params.limit = pageSize.value
      }
      
      if (enableSort && defaultSort) {
        params.sortBy = defaultSort.prop
        params.sortOrder = defaultSort.order
      }
      
      // 生成缓存键
      const currentCacheKey = `${cacheKey}_${JSON.stringify(params)}`
      
      // 尝试从缓存获取数据
      if (enableCache && !forceRefresh) {
        const cachedData = cache.get<{ data: T[]; total: number }>(currentCacheKey)
        if (cachedData) {
          tableData.value = cachedData.data
          if (enablePagination) {
            total.value = cachedData.total
          }
          loading.value = false
          return
        }
      }
      
      // 使用性能监控包装 API 调用
      const response = await measureApiCall(
        () => fetchApi(params),
        `fetchData_${cacheKey}`
      )
      
      tableData.value = response.data
      if (enablePagination) {
        total.value = response.total
      }
      
      // 缓存数据
      if (enableCache) {
        cache.set(currentCacheKey, response)
      }
    } catch (error) {
      console.error('获取数据失败:', error)
      ElMessage.error('获取数据失败')
    } finally {
      loading.value = false
    }
  }

  // 分页处理
  const handleSizeChange = (size: number) => {
    pageSize.value = size
    currentPage.value = 1
    fetchData()
  }

  const handleCurrentChange = (page: number) => {
    currentPage.value = page
    fetchData()
  }

  // 新增
  const handleAdd = (title = '新增') => {
    isEdit.value = false
    dialogTitle.value = title
    resetForm()
    dialogVisible.value = true
  }

  // 编辑
  const handleEdit = (item: T, title = '编辑') => {
    isEdit.value = true
    dialogTitle.value = title
    Object.assign(currentItem, item)
    dialogVisible.value = true
  }

  // 删除
  const handleDelete = async (id: string | number, confirmText = '确定删除该项吗？') => {
    if (!deleteApi) {
      ElMessage.warning('删除功能未配置')
      return
    }

    try {
      await ElMessageBox.confirm(confirmText, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })

      await measureApiCall(
        () => deleteApi(id),
        `deleteData_${cacheKey}`
      )
      
      // 清理相关缓存
      if (enableCache) {
        cache.keys().forEach(key => {
          if (key && key.startsWith(cacheKey)) {
            cache.remove(key)
          }
        })
      }
      
      ElMessage.success('删除成功')
      
      // 如果当前页没有数据了，回到上一页
      if (tableData.value.length === 1 && currentPage.value > 1) {
        currentPage.value -= 1
      }
      
      await fetchData()
    } catch (error: any) {
      if (error !== 'cancel') {
        console.error('删除失败:', error)
        ElMessage.error('删除失败')
      }
    }
  }

  // 提交表单
  const handleSubmit = async (formRef?: FormInstance) => {
    if (!formRef) {
      ElMessage.warning('表单引用未找到')
      return
    }

    try {
      await formRef.validate()
      
      if (isEdit.value) {
        if (!updateApi) {
          ElMessage.warning('更新功能未配置')
          return
        }
        await measureApiCall(
          () => updateApi(currentItem.id, currentItem),
          `updateData_${cacheKey}`
        )
        ElMessage.success('更新成功')
      } else {
        if (!createApi) {
          ElMessage.warning('创建功能未配置')
          return
        }
        await measureApiCall(
          () => createApi(currentItem),
          `createData_${cacheKey}`
        )
        ElMessage.success('创建成功')
      }
      
      // 清理相关缓存
      if (enableCache) {
        cache.keys().forEach(key => {
          if (key && key.startsWith(cacheKey)) {
            cache.remove(key)
          }
        })
      }
      
      dialogVisible.value = false
      await fetchData()
    } catch (error: any) {
      if (error.message) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    }
  }

  // 重置表单
  const resetForm = () => {
    Object.keys(currentItem).forEach(key => {
      delete currentItem[key]
    })
  }

  return {
    // 状态
    loading,
    tableData,
    currentPage,
    pageSize,
    total,
    dialogVisible,
    dialogTitle,
    isEdit,
    currentItem,
    
    // 方法
    fetchData,
    handleSizeChange,
    handleCurrentChange,
    handleAdd,
    handleEdit,
    handleDelete,
    handleSubmit,
    resetForm,
    
    // 计算属性
    hasData,
    isEmpty
  }
}